 //监听ag-grid全选事件，将全选的勾选改为筛选后的勾选
export default function useAgGridFilterSelector() {
  let lastSelectionRow:any = [];//记录最后一次选择的行的数据的ID（ag-grid的节点id，不是数据的id）
  let flag = true;//true为勾选筛选后的行，false为取消勾选全部行
  let isreturn = false;//代码中对节点setSelected会导致触发单选事件，没有找到解决办法，暂时使用定时器防止触发
const clickAllSelectors = (params: any) => {
  
  
  const selectedRowsID: any = []
     params.api.forEachNodeAfterFilter((row: any) => {
        selectedRowsID.push(row.id)
      })

  if (params.source === 'uiSelectAll') {
    
    isreturn = true
      //点击的全选的选择框
      lastSelectionRow = []
      // 过滤后的值
      const allNode: any = []
      params.api.forEachNode((node: any) => {
        allNode.push(node)
      })
    
      if (allNode.length ===params.api.getSelectedRows().length) {
        //全选状态  （区分取消全选还是全选）
       if (flag) {
        allNode.forEach((item: any) => {

          var rowNode =params.api.getRowNode(item.id) // 获取行节点
          let isSame = selectedRowsID.includes(item.id)
            if (isSame) {
               rowNode.setSelected(true) // 勾选行
              lastSelectionRow.push(rowNode.id)
            }
            else {
               rowNode.setSelected(false) // 不勾选行
            }
          
          
        })
        flag = false
        
       }else{
        flag = true
        allNode.forEach((item: any) => {
          var rowNode =params.api.getRowNode(item.id) // 获取行节点
          rowNode.setSelected(false) // 不勾选行      
        })
       }
       
      }else{
        flag = true
      }
      setTimeout(()=>{
        isreturn = false
      },500)
    }else{
      if (isreturn) return
      lastSelectionRow = []

      params.api.forEachNode((node: any) => {
        if(node.isSelected()){
          lastSelectionRow.push(node.id)
        }
      })
      if (selectedRowsID.length ===params.api.getSelectedRows().length) {
        flag = false
      }else{
        flag = true
      }
      
    }
}
//当筛选器变化时，不在筛选数据中的勾选的行清除
const onFilterChanged = (params: any)=>{
  let allNodeID:any = []
  flag = true
  params.api.forEachNodeAfterFilter((row: any) => {
    allNodeID.push(row.id)
  })
  lastSelectionRow.forEach((item:any)=>{
    if(!allNodeID.includes(item)){
      var rowNode =params.api.getRowNode(item) 
      rowNode.setSelected(false) // 不勾选行      
    }
  })

}
//每次刷新表格时调用此函数将flag设置为true
const resetAgFs = ()=>{
  flag = true
}
  return{
    clickAllSelectors,
    onFilterChanged,
    resetAgFs

  }
}